/**
 * @author:albert
 */

package com.bkbw.live.database.net.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.util.List;
import java.util.TreeMap;

import net.sf.json.JSONArray;

import org.apache.log4j.PropertyConfigurator;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bkbw.live.battle.database.bean.BagBeanManager;
import com.bkbw.live.battle.database.bean.EquipmentBean;
import com.bkbw.live.battle.database.bean.ItemsBean;
import com.bkbw.live.battle.database.bean.WeaponsBean;
import com.bkbw.live.common.net.codec.NetCodecFactory;
import com.bkbw.live.database.util.DatabasePool;
import com.bkbw.live.database.util.DatabaseUtil;

public class DatabaseServer {
	public static void main(String[] args) throws IOException {
		Logger logger = LoggerFactory.getLogger("mylog");
		PropertyConfigurator.configure("config/log4j.properties");
		PropertyConfigurator.configure("config/jdbc.properties");
		logger.debug("dbserver start");
		if (readDbInit()) {
			logger.debug("dbserver start succ");
		}
		else {
			logger.debug("dbserver start fail");
			return;
		}
		
		NioSocketAcceptor acceptor = new NioSocketAcceptor();
        acceptor.setBacklog(511);
        acceptor.setReuseAddress(true);
        //filter
//        LoggingFilter loggingFilter = new LoggingFilter();  
//        loggingFilter.setMessageSentLogLevel(LogLevel.NONE);
//        loggingFilter.setMessageReceivedLogLevel(LogLevel.NONE);
//        loggingFilter.setSessionClosedLogLevel(LogLevel.NONE);  
//        loggingFilter.setSessionCreatedLogLevel(LogLevel.NONE);  
//        loggingFilter.setSessionOpenedLogLevel(LogLevel.NONE);   
//        loggingFilter.setMessageReceivedLogLevel(LogLevel.NONE);
//        acceptor.getFilterChain().addLast( "logger", loggingFilter);
        //ProtocalCodecFilter过滤器非常重要，因为TCP/IP协议只能保证字节都能够按顺序全部传输，但是可能一条消息被分成多次事件，或者多条消息被合并成一次事件触发,
        acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new NetCodecFactory()));  
        acceptor.setHandler(new DatabaseServerHandler());  
        //设置一些配置属性
        acceptor.getSessionConfig().setReadBufferSize( 2048 );  
        acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );  
        
        int port = Integer.parseInt(args[0]);
        acceptor.bind(new InetSocketAddress(port)); 
	}
	
	private static boolean readDbInit() {
		Connection conn = null;
		try {
			conn = DatabasePool.getConnection();
			List<ItemsBean> listItemsBeans = DatabaseUtil.executeQueryInTransReturnBean(conn, "select * from mq_items", ItemsBean.class);
			TreeMap<Integer, ItemsBean> treeItems = new TreeMap<Integer, ItemsBean>();
			for (ItemsBean itemsBean : listItemsBeans) {
				treeItems.put(itemsBean.getId(), itemsBean);
			}
			List<EquipmentBean> listEquipmentBeans = DatabaseUtil.executeQueryInTransReturnBean(conn, "select * from mq_equipment", EquipmentBean.class);
			TreeMap<Integer, EquipmentBean> treeEquipment = new TreeMap<Integer, EquipmentBean>();
			for (EquipmentBean equipmentBean : listEquipmentBeans) {
				treeEquipment.put(equipmentBean.getId(), equipmentBean);
			}
			List<WeaponsBean> listWeaponsBeans = DatabaseUtil.executeQueryInTransReturnBean(conn, "select * from mq_weapons", WeaponsBean.class);
			TreeMap<Integer, WeaponsBean> treeWeapon = new TreeMap<Integer, WeaponsBean>();
			for (WeaponsBean weaponsBean : listWeaponsBeans) {
				treeWeapon.put(weaponsBean.getId(), weaponsBean);
			}
			BagBeanManager.getInstance().init(treeItems, treeEquipment, treeWeapon);
			return true;
		}
		catch (Exception e){
			e.printStackTrace();
			return false;
		}
		finally {
			try {
				if (conn != null) 
					DatabasePool.release(conn);
			}
			catch (Exception e){
				e.printStackTrace();
			}
		}
	}
}
